package com.ssi.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ssi.domain.user.User;

/**
 * 用于检测用户是否登陆的过滤器，如果未登录，则重定向到指的登录页面
 */
public class LoginFilter implements Filter {

	public void doFilter(ServletRequest servletRequest,
			ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		
		String requestURI = request.getRequestURI();
		System.out.println("你访问的地址是："+requestURI);
		String path=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()
		+request.getContextPath()+"/";
		request.getSession().setAttribute("path", path);
		if (user == null) {			
			if(requestURI.equals("/SSI/index.jsp") || requestURI.equals("/SSI/user/user_login.do")
			|| requestURI.equals("/SSI/goods/goods_queryAllGoods.do")
			|| requestURI.equals("/SSI/user/user_add.do")
		    || requestURI.equals("/SSI/user/user_checkLogin.do")
			|| requestURI.startsWith("/SSI/js")
			|| requestURI.startsWith("/SSI/index")
			|| requestURI.equals("/SSI/user/user_addUI.do")
			|| requestURI.equals("/SSI/shop/shop_shopIndex.do")
			|| requestURI.equals("/SSI/shop/shop_goodsType.do")
			){
				filterChain.doFilter(servletRequest, servletResponse);	
			}else{
				response.sendRedirect(request.getContextPath() + "/index.jsp");
			}
			
			
		} else {
			if(requestURI.equals("/SSI/logout")){
				session.removeAttribute("user");
				response.sendRedirect(request.getContextPath() + "/index.jsp");
			}else{
				filterChain.doFilter(servletRequest, servletResponse);
			}
			
		}

	}

	public void destroy() {
		// TODO Auto-generated method stub

	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}